package com.mengtian_tech.tju.dataquery.api.service;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mengtian_tech.tju.dataquery.api.db.EnhancedJdbcTemplate;
import com.mengtian_tech.tju.dataquery.api.model.dataAIMysql.SysMenu;
import com.mengtian_tech.tju.dataquery.api.model.dataAIMysql.SysRole;
import com.mengtian_tech.tju.dataquery.api.model.dataAIMysql.SysRoleMenu;
import com.mengtian_tech.tju.dataquery.api.model.dataAIMysql.SysRoleUser;
import com.mengtian_tech.tju.dataquery.api.model.tjuOracle.Employee;
import com.mengtian_tech.tju.dataquery.api.repo.dataAI.SysMenuRepo;
import com.mengtian_tech.tju.dataquery.api.repo.dataAI.SysRoleMenuRepo;
import com.mengtian_tech.tju.dataquery.api.repo.dataAI.SysRoleRepo;
import com.mengtian_tech.tju.dataquery.api.repo.dataAI.SysRoleUserRepo;
import com.mengtian_tech.tju.dataquery.api.repo.tjuOracle.EmployeeRepo;
import com.mengtian_tech.tju.dataquery.api.vo.User;

/**
 * 权限管理服务类
 */
@Service
@Transactional(value="dataAIJPATxManager")
public class PermissionService {
	
	@Autowired
	@Qualifier("enhancedJdbcTemplateDataAi")
	EnhancedJdbcTemplate jdbcTemplateDataAi;
	
	@Autowired
	@Qualifier("enhancedJdbcTemplateThimis")
	EnhancedJdbcTemplate jdbcTemplateTjuOracle;

	@Autowired
	@Qualifier("entityManagerDataAI")
	EntityManager entityManager;
	
	@Autowired
	EmployeeRepo employeeRepo;
	
	@Autowired
	SysMenuRepo sysMenuRepo;
	@Autowired
	SysRoleRepo sysRoleRepo;
	@Autowired
	SysRoleMenuRepo sysRoleMenuRepo;
	@Autowired
	SysRoleUserRepo sysRoleUserRepo;
	
	 
	public List<SysRole> getRoleList(){
		return this.sysRoleRepo.getRoleList();
	}
	
	public void deleteRole(String id) {
		SysRole role = this.sysRoleRepo.findById(id).orElse(null);
		this.sysRoleRepo.delete(role);
	}
	
	public void addRole(SysRole role) {
		this.entityManager.persist(role);		
	}
	
	public void updateRole(SysRole role) {
		SysRole target = this.entityManager.find(SysRole.class, role.getId());
		target.setName(role.getName());
		
		this.entityManager.persist(target);
	}
	
	/**
	 * 保存角色菜单
	 * @param list
	 */
	public void saveRoleMenu(List<SysRoleMenu> list) {
		
		for(SysRoleMenu rm:list) {
			this.entityManager.persist(rm);
		}
		
	}
	
	/**
	 * 删除角色授权菜单
	 * @param roleId
	 */
	public void deleteRoleMenu(String roleId) {
		Query q =  this.entityManager.createQuery("delete from SysRoleMenu a where a.roleId = ?1");
		q.setParameter(1, roleId);
		q.executeUpdate();
	}
	
	
	public List<SysRoleMenu> getRoleMenus(String roleId) {
		TypedQuery<SysRoleMenu> q =  this.entityManager.createQuery("  from SysRoleMenu a where a.roleId = ?1",SysRoleMenu.class);
		q.setParameter(1, roleId);
		return q.getResultList();
	}
	
	
	/**
	 * 获取已授权的用户
	 * @return
	 */
	public List<User> getGrantUserList(int pageNo,int pageSize,String id,String name) {
		String sql="select user_id id,user_name name from sys_role_user where 1=1  ";
		
		List<Object> params = new ArrayList<Object>();
		if(StringUtils.isNotEmpty(id)) {
			sql += " and user_id = ? ";
			params.add(id);
		}
		
		if(StringUtils.isNotEmpty(name)) {
			sql += " and user_name like ? ";
			params.add("%"+name+"%");
		}
		
		sql += "GROUP BY user_id, user_name  limit ?,? ";
		
		params.add((pageNo-1)*pageSize);
		params.add(pageSize);
		
		List<User> list =  this.jdbcTemplateDataAi.queryForList(sql,User.class,params.toArray());
		
		//循环获取用户角色
		for(User user : list) {
			List<SysRole> roles = getUserRoles(user.getId());
			user.setUserRoles(roles);
		}
		
		return list;
	}
	
	/**
	 * 获取已授权的用户
	 * @return
	 */
	public Long getGrantUserListCount() {
		String sql="select  count(1) cnt from sys_role_user GROUP BY user_id, user_name";
		List<Long> list =  this.jdbcTemplateDataAi.queryForList(sql,Long.class);
		if(list.size() > 0) {
			return list.get(0);
		}else {
			return 0l;
		}
	}
	
	
	/**
	 * 获取用户被授权的角色
	 * @param userId
	 * @return
	 */
	public List<SysRole> getUserRoles(String userId) {
		String sql="select  t2.id , t2.name   from sys_role_user t1, sys_role t2 where   t1.user_id = ? and t1.role_id = t2.id   ";
		return this.jdbcTemplateDataAi.queryForList(sql,SysRole.class,userId);
	}
	
	
	public void  deleteUserRoles(String userId) {
		String sql="delete  from sys_role_user where   user_id = ? ";
		this.jdbcTemplateDataAi.update(sql,userId);
	}
	
	public void  saveUserRoles(String userId,List<SysRole> roles) {
		String username = this.getEmployeeName(userId);
		for(SysRole r:roles) {
			SysRoleUser ru = new SysRoleUser();
			ru.setUserId(userId);
			ru.setRoleId(r.getId());
			ru.setUserName(username);
			sysRoleUserRepo.save(ru);
 		}
	}
	
	public List<SysMenu> getAllMenuList(){
		List<SysMenu> result =  this.sysMenuRepo.getTopMenus();
		
		for(SysMenu m:result) {
			List<SysMenu> children = this.sysMenuRepo.getChildren(m.getId());
			m.setChildren(children);
		}
		
		return result;
		
	}

	/**
	 * 保存用户角色
	 * @param role
	 */
	public void saveRole(SysRole role) {
		role.setDeleteFlag(0);
		this.sysRoleRepo.save(role);
		this.sysMenuRepo.flush();
		
		
		//删除所有授权菜单
		this.sysRoleMenuRepo.deleteByRoleId(role.getId());
		
		
		//保存菜单
		List<SysMenu> menus = role.getMenuList();
		for(SysMenu m : menus) {
			SysRoleMenu rm = new SysRoleMenu();
			rm.setRoleId(role.getId());
			rm.setMenuId(m.getId());
			this.sysRoleMenuRepo.save(rm);
		}
	}

	public String getEmployeeName(String id) {
		
		
		Employee  employee = 	employeeRepo.findById(id).orElse(null);
		
		if(employee != null) return employee.getName();
		return "";
	}
	
	/**
	 * 获取用户权限列表
	 * @return
	 */
	public List<String> getUserPerms(String userId){
		return  this.jdbcTemplateDataAi.queryForList("select  DISTINCT( t2.menu_id ) menu from sys_role_user t1, sys_role_menu t2  where t1.user_id=  ? "
				+ "and t2.role_id = t1.role_id  ",String.class, userId);
	}
	
}
